package com.yokead.service.rewrite;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.jiangzeyin.StringUtil;
import com.yokead.system.log.SystemLog;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
 * Created by Administrator on 2017/5/11.
 */
@Service
public class EditRewriteServer {
    /**
     * 刪除原有的跳转
     *
     * @param loc
     * @param path
     * @return
     */
    public StringBuffer delRewrite(String loc, String path, boolean urlAll) {
        if (!loc.endsWith("/") && !loc.endsWith(".html")) {
            loc = loc + "/";
        }
        BufferedReader bufferedReader = null;
        try {
            bufferedReader = new BufferedReader(new FileReader(new File(path)));
            String line;
            StringBuffer stringBuffer = new StringBuffer();
            while ((line = bufferedReader.readLine()) != null) {
                if (StringUtil.isEmpty(line)) {
                    continue;
                }
                if (urlAll) {
                    int locCount = line.lastIndexOf("/") - line.indexOf("/");
                    int newLocCount = loc.lastIndexOf("/") - loc.indexOf("/");
                    if (line.contains(loc) && (locCount == newLocCount && locCount != 0)) {
                        //line = line.trim();
                        if (!line.endsWith("}")) {
                            while ((line = bufferedReader.readLine()) != null) {
                                line = line.trim();
                                if (line.endsWith("}")) {
                                    break;
                                }
                            }
                        }
                    } else {
                        stringBuffer.append(line).append(System.lineSeparator());
                    }
                } else {
                    boolean find = false;
                    if (line.contains(loc)) {
                        String[] lineInfo = StringUtil.stringToArray(line);
                        for (String temp : lineInfo) {
                            if (temp.equals(loc)) {
                                find = true;
                                break;
                            }
                        }
                    }
                    if (find) {
                        //line = line.trim();
                        if (!line.endsWith("}")) {
                            while ((line = bufferedReader.readLine()) != null) {
                                line = line.trim();
                                if (line.endsWith("}")) {
                                    break;
                                }
                            }
                        }
                    } else {
                        stringBuffer.append(line).append(System.lineSeparator());
                    }
                }
            }
            return stringBuffer;
        } catch (IOException e) {
            SystemLog.ERROR().error("删除跳转", e);
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e) {
                SystemLog.ERROR().error("删除跳转", e);
            }
        }
        return null;
    }

    /**
     * 保存修改的跳转
     *
     * @param oldLoc
     * @param file
     * @param newLoc
     * @param toUrl
     * @param par
     */
    public void saveRewrite(String oldLoc, String file, String newLoc, String inUrl, String toUrl, boolean urlAll, boolean par) throws IOException {
        CharSequence info = createRewrite(newLoc, toUrl, par);
        StringBuffer stringBuffer = delRewrite(oldLoc, file, urlAll);
        if (stringBuffer == null) {
            throw new RuntimeException("操作失败，请联系管理员");
        }
        //System.out.println(stringBuffer);

        int end = stringBuffer.lastIndexOf("}");
        //appendToLine(file, end, info);
        //stringBuffer.deleteCharAt(end + 1);
        stringBuffer.insert(end, info);
        // 写入文件
        //.writeFile(file, stringBuffer);
        FileUtil.writeString(stringBuffer.toString(), file, CharsetUtil.CHARSET_UTF_8);
        //EncodeFileUtil.writeFile(file, stringBuffer);
        //System.out.println(info);
        saveRewriteLog(file, oldLoc, newLoc, inUrl, toUrl, urlAll, par);
        //System.out.println(stringBuffer);
    }


    private String saveRewriteLog(String path, String oldLoc, String newLoc, String inputUrl, String toUrl, boolean urlAll, boolean par) {
        File conf_file = new File(path);
        String name = conf_file.getName().replace(".conf", ".rewrite_log");
        File file = new File(conf_file.getParent(), name);
        BufferedReader bufferedReader = null;
        try {
            StringBuffer stringBuffer = new StringBuffer();
            String oldInfo = null;
            if (file.exists()) {
                bufferedReader = new BufferedReader(new FileReader(file));
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    String[] lineInfo = StringUtil.stringToArray(line, ",");
                    String tag = lineInfo[0];
                    if (tag.equals(oldLoc)) {
                        oldInfo = line;
                        continue;
                    } else {
                        if (StringUtil.isEmpty(line)) {
                            continue;
                        }
                        stringBuffer.append(line).append(System.lineSeparator());
                    }
                }
            }
            stringBuffer.append(newLoc).append(",")
                    .append(inputUrl).append(",")
                    .append(toUrl).append(",")
                    .append(urlAll).append(",").append(par).append(System.lineSeparator());
            FileUtil.writeString(stringBuffer.toString(), file.getPath(), CharsetUtil.CHARSET_UTF_8);
            return oldInfo;
        } catch (IOException e) {
            SystemLog.ERROR().error("保存跳转", e);
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e) {
                SystemLog.ERROR().error("保存跳转", e);
            }
        }
        return null;
    }

    /**
     * 创建跳转节点
     *
     * @param loc
     * @param toUrl
     * @param par
     * @return
     */
    private StringBuffer createRewrite(String loc, String toUrl, boolean par) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("\tlocation ").append(loc).append(" ").append("{").append("\t\n");
        stringBuffer.append("\t\t").append("rewrite \"^/(.*)$\" ").append(toUrl);
        if (par) {
            stringBuffer.append("$2");
        }
        stringBuffer.append(" ").append("break;").append("\t\n");
        stringBuffer.append("\t}").append("\t\n");
        return stringBuffer;
    }
}
